package com.example.demoweb.util.file;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.example.demoweb.constant.Constants;
import com.example.demoweb.util.Data;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSFile;
/**
 * 文件操作工具类
 * @author jhq
 *
 */
@Component
@Transactional
public class FileUtil {
	
	@Autowired
	private GridFsTemplate gridFsTemplate;
	
	@Autowired
	private Base64Convert base64Convert;
	
    /**
     * 文件上传
     * 返回数据中封装了该文件的id
     * @param file
     */
    public Data<String> upload(MultipartFile file) {
    	Data<String> data = new Data<String>();
    	try {
    		GridFSFile gridFSFile = gridFsTemplate.store(file.getInputStream(), file.getOriginalFilename(), file.getContentType());
    		data.setResult(Constants.SUCCESS_CODE);
    		data.setResultData(gridFSFile.getId().toString());
        	return data;
        } catch (Exception e) {
        	data.setResult(Constants.FAIL_CODE);
        	data.setMsgcode(Constants.FILE_UPLOAD_ERROR);
        	data.setMessage("文件上传失败，请联系管理员。");
            return data;
       }
    }
    /**
     * 获取图片的base64字符串
     * @throws IOException 
     */
    public Data<String> getBase64Info(String id) throws IOException{
    	Data<String> data = new Data<String>();
    	String resultStr = "";
    	Query query = new Query();
    	query.addCriteria(Criteria.where("_id").is(new ObjectId(id)));
        GridFSDBFile resultFile = gridFsTemplate.findOne(query);
    	//List<GridFSDBFile> list = gridFsTemplate.find(query);
    	//GridFSDBFile resultFile = list.get(0);
        if (resultFile!=null) {
        	InputStream in = resultFile.getInputStream();
        	String baseStr = base64Convert.fileToBase64(in);
        	resultStr = "data:image/jpeg;base64," + baseStr;
        	data.setResult(Constants.SUCCESS_CODE);
        	data.setResultData(resultStr);
		}else {
			data.setResult(Constants.FAIL_CODE);
			data.setMsgcode(Constants.FAIL_DATA_EMPTY);
        	data.setMessage("无对应图片");
		}
        return data;
    }
    
    /**
     * 根据文件id下载大附件
     * @param response
     * @param id
     */
    public void download(HttpServletResponse response,String id) {
    	Query query = new Query();
    	query.addCriteria(Criteria.where("_id").is(new ObjectId(id)));
        GridFSDBFile resultFile = gridFsTemplate.findOne(query);
        if (resultFile!=null) {
			try {
				InputStream in = resultFile.getInputStream();
				response.addHeader("Content-Disposition", "attachment;filename="+new String((resultFile.getFilename()).getBytes("GB2312"),"iso8859-1"));
				response.setContentType("application/octet-stream");	
				try {
					IOUtils.copy(in,response.getOutputStream());    
				} catch (IOException e) {
					e.printStackTrace();
				}finally{
					in.close();
				}
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
    }
}
